<?php

namespace App\Http\Controllers\Api;

use App\Models\Api\Ad;
use App\Models\Api\Goods;
use App\Models\Api\Store;
use App\Tools\Images;
use App\Tools\Sms;
use App\Tools\ApiService;
use App\Service\SmsService;
use Illuminate\Http\Request;
use App\Models\Api\AdminUser;
use Illuminate\Support\Facades\Redis;

class LoginController
{

    /**
     * 密码登录
     */
    public function passLogin(Request $request)
    {
        $username = $request->input("username");
        $password = $request->input("password");

        # 参数验证
        if (empty($username)) {
            return errorMsg("请输入用户名");
        }
        if (empty($password)) {
            return errorMsg("请输入密码");
        }

        # 获取商户信息
        $info = AdminUser::getInfo(['username' => $username]);

        if (!$info) {
            return errorMsg("用户不存在");
        }
        $string = md5($password . $info['safe']);
        if ($info['password'] != $string) {
            return errorMsg("密码错误");
        }
        if ($info['store_id'] == 0) {
            return errorMsg("用户不存在");
        }
        if ($info['status'] == 2) {
            return errorMsg("此用户已被禁止登录，请联系管理员");
        }
        $store = Store::getInfoById($info['store_id']);
        if (!$store) {
            return errorMsg("商户不存在");
        }
        $status = [1 => '资质认定中', 2 => '审核失败', 3 => '存续', 4 => '升级认定中', 5 => '资质过期', 6 => '待存续'];
        if (in_array($store['status'], [1, 2, 5, 6])) {
            return errorMsg("商户" . $status[$store['status']] . "，请联系管理员");
        }
        if (strtotime($store['agent_end_time']) <= time()) {
            return errorMsg("商户资质过期，请联系管理员");
        }

        # 生成token
        $data = ['id' => $info['id'], 'store_id' => $info['store_id'], 'mobile' => $info['mobile'], 'username' => $info['username']];
        $token = ApiService::appTokenLogin($info['id'], $data);

        # 更新登录信息
        AdminUser::where('id', $info['id'])->increment('login_num', 1, ['login_time' => time(), 'login_ip' => $_SERVER['REMOTE_ADDR']]);

        return successMsg(['username' => $info['username'], 'mobile' => $info['mobile'], 'token' => $token]);
    }

    /**
     * 手机号登录
     * @param Request $request
     */
    public function mobileLogin(Request $request)
    {
        $code = $request->input('code');
        $mobile = $request->input('mobile');
        # 参数验证
        if (empty($mobile)) {
            return errorMsg("请输入手机号");
        }
        if (!preg_match('/^1[345789][0-9]{9}$/', $mobile)) {
            return errorMsg('手机号格式不正确');
        }
        if (empty($code)) {
            return errorMsg("请输入验证码");
        }

        # 验证码检测
        $key = 'SMS:' . $mobile;
        $value = Redis::GET($key);
//        if (!$value || $value != $code) {
//            return errorMsg('验证码错误');
//        }

        # 获取商户信息
        $info = AdminUser::getInfo(['mobile' => $mobile]);
        if (!$info) {
            return errorMsg("用户不存在");
        }
        if ($info['store_id'] == 0) {
            return errorMsg("用户不存在");
        }
        if ($info['status'] == 2) {
            return errorMsg("此用户已被禁止登录，请联系管理员");
        }
        $store = Store::getInfoById($info['store_id']);
        if (!$store) {
            return errorMsg("商户不存在");
        }
        $status = [1 => '资质认定中', 2 => '审核失败', 3 => '存续', 4 => '升级认定中', 5 => '资质过期', 6 => '待存续'];
        if (in_array($store['status'], [1, 2, 5, 6])) {
            return errorMsg("商户" . $status[$store['status']] . "，请联系管理员");
        }
        if (strtotime($store['agent_end_time']) <= time()) {
            return errorMsg("商户资质过期，请联系管理员");
        }

        # 生成token
        $data = ['id' => $info['id'], 'store_id' => $info['store_id'], 'mobile' => $info['mobile'], 'username' => $info['username']];
        $token = ApiService::appTokenLogin($info['id'], $data);

        # 更新登录信息
        AdminUser::where('id', $info['id'])->increment('login_num', 1, ['login_time' => time(), 'login_ip' => $_SERVER['REMOTE_ADDR']]);

        return successMsg(['username' => $info['username'], 'mobile' => $info['mobile'], 'token' => $token]);
    }

    /**
     * 发送短信验证码
     * @param Request $request
     * @throws \AlibabaCloud\Client\Exception\ClientException
     */
    public function sendCode(Request $request)
    {
        $ip = $request->ip();
        $mobile = $request->input('mobile');

        Sms::sendCode($mobile, $ip);

        return successMsg();
    }

    // 代理商申请
    public function applyStore(Request $request)
    {
        $params = $request->input();
        if (empty($params['store_name'])) {
            errorMsg('请填写企业名');
        }
        if (empty($params['principal_name'])) {
            errorMsg('请填写联系人');
        }
        if (empty($params['principal_mobile'])) {
            errorMsg('请填写联系电话');
        }
        $id = Store::where(['principal_mobile' => $params['principal_mobile']])->value('id');
        if ($id) {
            errorMsg('该手机号已提交申请');
        }
        if (empty($params['principal_card_a']) || empty($params['principal_card_b'])) {
            errorMsg('请上传身份证正反页');
        }
        if (empty($params['company_license'])) {
            errorMsg('请上传营业执照');
        }
        if (empty($params['company_license_yy'])) {
            errorMsg('请上传许可执照');
        }
        $info['store_sn'] = pdStoreSn();
        $info['store_name'] = $params['store_name'];
        $info['principal_name'] = $params['principal_name'];
        $info['principal_mobile'] = $params['principal_mobile'];
        $info['principal_card_sn'] = $params['principal_card_sn'];
        $info['principal_card_a'] = $params['principal_card_a'];
        $info['principal_card_b'] = $params['principal_card_b'];
        $info['company_license'] = $params['company_license'];
        $info['company_license_yy'] = $params['company_license_yy'];
        $info['company_registered_capital'] = $params['company_registered_capital'];
        $info['company_business_scope'] = $params['company_business_scope'];
        $info['status'] = 0;
        $info['apply_time'] = time();
        $info['created_at'] = time();
        Store::insert(array_filter($info));
        successMsg();
    }

    /**
     * 商品列表
     * @return mixed
     */
    public function goodsList()
    {
        $list = Goods::from('goods as g')
            ->select(['g.id', 'g.goods_sn', 'g.goods_name', 'g.goods_price', 'g.mini_quantity', 'g.goods_img', 'c.cate_name'])
            ->leftJoin('goods_category as c', 'c.id', '=', 'g.cate_id')
            ->where([
                'g.status' => 1, 
                'g.promotion' => 0,
                'g.is_group' => 0  // 添加组合商品过滤
            ])
            ->orderBy('g.id', 'desc')
            ->paginate(100);
        foreach ($list as $kk => $vv) {
            $list[$kk]['goods_id'] = $vv['id'];
            $list[$kk]['sale_price'] = $vv['goods_price'];
        }
        return $list;
    }

    // 上传图片
    public function imageUpload(Request $request)
    {
        $image_url = Images::uploadImg($request->file('file'));
        $returnData['image'] = IMAGE_URI . $image_url;
        successMsg($returnData);
    }

    // 广告图
    public function adList()
    {
        $list = Ad::getListByCateId(1);
        successMsg($list);
    }
}
